import { message, TimePicker } from 'antd';
import moment, { Moment } from 'moment';
import React, { ReactElement, useState } from 'react';

interface Props {
  /**传入的值 */
  timeValue: [Moment, Moment];
  /**回调值 */
  callbackfn: (timeRange: [Moment, Moment]) => void;
}

export default function TimeRangePicker({ timeValue, callbackfn }: Props): ReactElement {
  const [begin, setBegin] = useState(timeValue[0]);
  const [end, setEnd] = useState(timeValue[1]);
  return (
    <>
      <TimePicker
        allowClear={false}
        format="HH:mm"
        style={{ width: 100 }}
        value={begin}
        onChange={(val: Moment | null, str: string) => {
          // val在点击此刻时不准确
          console.log('选择的开始时间', str);
          const new_val = moment(str, 'HH:mm');
          if (!new_val) {
            return;
          }
          console.log('结束时间***', end?.format('HH:mm'));
          if (end && new_val.isSameOrAfter(end)) {
            message.info('开始时间需要早于结束时间');
          } else {
            setBegin(new_val);
            const timeRange: [Moment, Moment] = [new_val, end];
            callbackfn(timeRange);
          }
        }}
      />
      <span style={{ padding: '0 5px' }}>-</span>
      <TimePicker
        allowClear={false}
        format="HH:mm"
        style={{ width: 100 }}
        value={end}
        onChange={(val: Moment | null, str: string) => {
          console.log('选择的结束时间', str);
          const new_val = moment(str, 'HH:mm');
          if (!new_val) {
            return;
          }
          console.log('开始时间***', begin?.format('HH:mm'));
          if (begin && new_val.isSameOrBefore(begin)) {
            message.info('结束时间需要晚于开始时间');
          } else {
            setEnd(new_val);
            const timeRange: [Moment, Moment] = [begin, new_val];
            callbackfn(timeRange);
          }
        }}
      />
    </>
  );
}
